<template>
	<view class="container">
		<view class="content">
			<owner-info :item="carInfo"></owner-info>
			<view class="order-info">
				<text class="txt1">订单信息</text>
				<view class="txt2">
					<text class="txt2-1">销售</text>
					<text class="txt2-2">{{orderInfo.employeeName}}</text>
				</view>
				<view class="txt2">
					<text class="txt2-1">业务渠道</text>
					<text class="txt2-2">暂无</text>
				</view>
				<view class="txt2">
					<text class="txt2-1">订单编号</text>
					<text class="txt2-2">{{orderInfo.saleId}}</text>
				</view>
				<view class="txt2">
					<text class="txt2-1">下单时间</text>
					<text class="txt2-2">{{orderInfo.createTime}}</text>
				</view>
				<view class="txt2">
					<text class="txt2-1">安排订单</text>
					<text
						class="txt2-2">{{orderInfo.orderSettlement&&orderInfo.orderSettlement.settlementItemList[0].createTime}}</text>
				</view>
				<view class="txt2">
					<text class="txt2-1">安排师傅</text>
					<text class="txt2-2">{{orderInfo.setEmployeeTime}}</text>
				</view>
			</view>
			<view class="add-info">
				<view class="title">
					<text class="txt">车辆照片(正面、侧面45°、侧后45°、背面)</text>
				</view>
				<view class="photo-content">
					<template v-for="(item,index) in carPhtoto" :key="index">
						<image class="photo" :src="item" mode="aspectFill" @click="previewImage(carPhtoto,index)">
						</image>
					</template>
				</view>
			</view>
			<view class="add-info">
				<view class="title">
					<text class="txt">服务项目</text>
				</view>
				<view class="chosenContent"
					style="background-color: #ededf4;display: flex;justify-content: space-between;align-items: center;flex-direction: row;"
					v-for="(item,index) in orderService">
					<view>
						<view class="top">
							<view class="serv">
								<text class="service">{{item.name}}</text>
								<text v-if="item.productSku" class="product">{{item.productSku.productName}}</text>
							</view>
						</view>
						<view style="display: flex;align-items:center; padding: 5rpx 0;">
							<text v-if="item.productSku" class="price1">{{item.productSku.totalPrice}}</text>
							<text v-else class="price1">{{item.actualPrice}}</text>
							<text class="price2">元</text>
						</view>
					</view>
					<view style="display: flex;align-items: center;gap: 5rpx;">
						<text class="txt2-2" style="color:#c6c6c6;"
							v-if="item.employeeId&&store.currentUser.id!=item.employeeId">{{item.employeeName}}
						</text>
						<text class="txt2-2" style="color: #6074C1;" v-else-if="isSelectList[index]">自己</text>

						<uni-icons v-if="canSelectFlag && (store.currentUser.id==item.employeeId || !item.employeeId)"
							:type="isSelectList[index] ? 'checkbox' : 'circle'"
							:color="isSelectList[index] ? (item.employeeId&&store.currentUser.id!=item.employeeId?'#c6c6c6':'#6074C1') : '#c6c6c6'"
							size="26" @click="change_isSelect(item,index)">
						</uni-icons>
						<uni-icons v-else :type="isSelectList[index] ? 'checkbox' : 'circle'"
							:color="isSelectList[index] ? (item.employeeId&&store.currentUser.id!=item.employeeId?'#cecece':'#6074C1') : '#c6c6c6'"
							size="26">
						</uni-icons>
					</view>
				</view>
			</view>
			<view class="add-info">
				<view class="title">
					<text class="txt">施工主管</text>
				</view>
				<view class="chosenContent" style="border: none;">
					<view class="manager">
						<!-- <image v-if="'avatar' in item" :src="item.avatar" mode="heightFix"></image> -->
						<text class="name">{{orderInfo.managerName}}</text>
					</view>
				</view>
			</view>
			<view class="add-info">
				<view class="title">
					<text class="txt">安排师傅</text>
				</view>
				<view v-if="workerList" class="chosenContent" style="border: none;" v-for="(item,index) in workerList"
					:key="item.id">
					<view class="manager">
						<image v-if="'avatar' in item" :src="item.avatar" mode="heightFix">
						</image>
						<text class="name" :style="store.currentUser.id==item.id?'color:#6074C1':''">{{item.name}}
						</text>
					</view>
				</view>
			</view>
			<view v-if="canSelectFlag" class="btn" @click="arrenge">
				开始施工
			</view>
			<up-divider v-else text="已选择,请等待其他师傅选择项目"></up-divider>
		</view>

	</view>

</template>

<script setup>
	import {
		ref,
		reactive,
		computed
	} from 'vue';
	import {
		onLoad,
		onShow,
		onUnload
	} from "@dcloudio/uni-app";
	import {
		api_get_order_easy_info,
		api_saleOrder_getInfo,
		api_saleOrder_updateBuildStatus,
		api_serviceEmployee_list,
		api_serviceEmployee_receiveService,
		api_serviceEmployee_getServiceByEmployeeId
	} from "../../../../apis/apis.js"
	import {
		useMainStore
	} from '@/utils/store.js';

	const store = ref(useMainStore());
	const carInfo = ref({}); //订单简易信息
	const orderInfo = ref({}); //订单其他信息
	const orderService = ref([]); //订单选择的服务
	const carPhtoto = ref([]); //订单车辆图片
	const swipeShow = ref(false);
	const workerList = ref([]);
	const isSelect = ref(false);
	const isSelectList = ref([]); // 存储每个 item 的选中状态
	const selectCount = ref(0); //选择了几个
	const selectIds = ref([]); //选择的项目id
	const orderServiceIds = ref([]); //订单里的服务项目id的列表
	const canSelectFlag = ref(true)

	const change_isSelect = (item, index) => {
		// 反转当前选中状态
		isSelectList.value[index] = !isSelectList.value[index];

		function unique(arr1) {
			const res = new Map()
			return arr1.filter((item) => !res.has(item.employeeId) && res.set(item.employeeId, 1)).length
		}

		// 获取剩余未选人数
		let rePerNum = workerList.value.length - unique(orderService.value)
		// 获取剩余待选项数量
		let reSelNum = orderService.value.length - isSelectList.value.filter(item => item).length;
		console.log(rePerNum, reSelNum);
		// 检查是否选择超过限制
		if (reSelNum >= rePerNum) {
			// 更新 selectIds 数组
			selectIds.value = []; // 清空之前的选中 IDs
			isSelectList.value.forEach((isSelected, idx) => {
				if (isSelected) {
					selectIds.value.push(orderService.value[idx].serviceItemId); // 压入选中的服务项 ID
				}
			});
			// 打印当前选中的 selectIds 列表
		} else {
			uni.showToast({
				title: "选太多了！",
				icon: "error"
			});
			// 还原选中状态
			isSelectList.value[index] = !isSelectList.value[index];
			selectCount.value = isSelectList.value.filter(item => item).length;
		}
	};

	// 点击预览图片
	const previewImage = (carPhtoto, index) => {
		uni.previewImage({
			current: index,
			urls: carPhtoto
		});
	};

	// 点击安排订单
	const arrenge = async () => {
		let param;
		let newArr = selectIds.value.filter(item => {
			return !(orderService.value.find(item_o => {
				return item_o.serviceItemId == item
			}).employeeId)
		})
		console.log(orderService.value);
		console.log(newArr);

		if (newArr.length == 0) {
			uni.showToast({
				title: "请选择服务项目!",
				icon: "error"
			});
			return;
		} else {
			param = {
				serviceItemIds: newArr,
				orderServiceId: orderInfo.value.orderService.orderServiceId
			};
		}
		// 传入选择的服务项目
		try {
			await api_serviceEmployee_receiveService(param);
			uni.navigateBack({
				delta: 1,
				success: () => {
					uni.showToast({
						title: "选择成功",
						icon: "success"
					});
				}
			});
		} catch (e) {
			uni.showToast({
				title: e.msg,
				icon: 'none'
			});
		}
	};

	onShow(async () => {
		// 初始化 isSelectList 数组，使其长度与 orderService 相同，并且默认都为 false（未选中）
		isSelectList.value = orderService.value.map(() => false);

		let param = {
			saleId: store.value.orderId
		};
		// 查询订单简易信息
		try {
			let res1 = await api_get_order_easy_info(param);
			carInfo.value = res1.data;
		} catch (e) {
			uni.showToast({
				title: e.msg,
				icon: "none"
			});
		}
		// 查询订单其他信息
		try {
			let res2 = await api_saleOrder_getInfo(param);
			orderInfo.value = res2.data; // 订单其他信息
			orderService.value = res2.data.orderService.serviceItemList; // 订单的服务项目列表
			orderServiceIds.value = orderService.value.map(item => item.serviceItemId); // 订单的服务项目id列表
			workerList.value = res2.data.orderService.employeeInfos;
			carPhtoto.value = JSON.parse(res2.data.carImage); // 订单的汽车图片
			selectIds.value = []
			console.log(orderService.value);
			orderService.value.forEach(item => {
				if (item.employeeId) {
					selectIds.value.push(item.serviceItemId)
				}
			})
			// selectIds.value = res.data.map(item => item.employeeId?item.);
			// 更新 isSelectList
			isSelectList.value = orderServiceIds.value.map(serviceId => selectIds.value.includes(serviceId));
			selectCount.value = isSelectList.value.filter(item => item).length;
			// 打印当前选中的 selectIds 列表
			console.log(selectIds.value);


		} catch (e) {
			uni.showToast({
				title: e.msg,
				icon: "none"
			});
		}
		// 查询师傅选了哪些服务
		try {
			let res = await api_serviceEmployee_getServiceByEmployeeId({
				employeeId: store.value.currentUser.id,
				orderServiceId: orderInfo.value.orderService.orderServiceId
			});
			if (res.data.length) {
				canSelectFlag.value = false
			}

		} catch (e) {
			uni.showToast({
				title: e.msg,
				icon: "none"
			});
		}
	});

	onUnload(() => {

	});
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-bottom: calc(calc(env(safe-area-inset-bottom)) + 10rpx);

		.content {
			display: flex;
			flex-direction: column;
			align-items: center;
			background-color: #ededf4;
			width: 750rpx;
			padding-top: 36rpx;
			height: auto;

			.order-info {
				background-color: $main-background-color;
				width: 700rpx;
				height: auto;
				display: flex;
				flex-direction: column;
				align-items: left;
				gap: 10rpx;
				margin-top: 50rpx;

				.txt1 {
					font-family: Alibaba_PuHuiTi_Medium;
					font-weight: 500;
					font-size: 34rpx;
					color: $font-primary-color;
				}

				.txt2 {
					display: flex;
					align-items: center;

					.txt2-1 {
						width: 160rpx;
						font-family: Alibaba_PuHuiTi_Light;
						font-weight: 300;
						font-size: 34rpx;
						color: $font-primary-color;
						margin-right: 30rpx;
					}

					.txt2-2 {
						font-family: Alibaba_PuHuiTi_Light;
						font-weight: 300;
						font-size: 36rpx;
						color: $font-sub-color;
					}
				}
			}
		}

		.add-info {
			margin-top: 50rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.title {
				width: 700rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.txt {
					font-family: Alibaba_PuHuiTi_Medium;
					font-weight: 500;
					font-size: 34rpx;
					color: $font-primary-color;
				}

				.add {
					width: 36rpx;
					height: 36rpx;
				}
			}

			.photo-content {
				width: 700rpx;
				display: flex;
				justify-content: space-between;

				.photo {
					width: 170rpx;
					height: 170rpx;
					margin-top: 32rpx;
				}
			}

			.chosenContent {
				width: 700rpx;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				align-items: left;

				border-bottom: 1rpx solid $border-color;

				.top {
					padding-top: 20rpx;
					width: 100%;
					// display: flex;
					// justify-content: space-between;
					align-items: center;

					.serv {
						display: flex;
						align-items: center;

						.service {
							font-family: Alibaba_PuHuiTi_Light;
							font-weight: 300;
							font-size: 34rpx;
							color: $font-primary-color;
							margin-right: 10rpx;
						}

						.product {
							font-family: Alibaba_PuHuiTi_Light;
							font-weight: 300;
							font-size: 34rpx;
							color: $font-sub-color;
						}
					}
				}
			}

			.price1 {
				font-family: Alibaba_PuHuiTi_Thin;
				font-weight: 250;
				font-size: 34rpx;
				color: $font-sub-color;
				width: 84rpx;
				text-align: center;
			}

			.price2 {
				font-family: Alibaba_PuHuiTi_Thin;
				font-weight: 300;
				font-size: 34rpx;
				color: $font-9e-color;
			}

			.manager {
				width: 100%;
				display: flex;
				align-items: center;
				padding: 18rpx 0 10rpx 0;
				background-color: #ededf4;

				image {
					width: 40rpx;
					border-radius: 100rpx;
					overflow: hidden;
					height: 100rpx;
				}

				.name {
					font-family: Alibaba_PuHuiTi_Light;
					font-weight: 300;
					font-size: 34rpx;
					color: $font-sub-color;
					margin-left: 14rpx;
				}
			}
		}

		.btn {
			width: 700rpx;
			height: 80rpx;
			border-radius: 10rpx;
			overflow: hidden;
			background-color: $primary-color;
			font-family: Alibaba_PuHuiTi_Regular;
			font-weight: 400;
			font-size: 38rpx;
			color: white;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-top: 50rpx;
		}
	}
</style>